<template>
  <div class="experience-page">
    <!-- 顶部操作栏 -->
    <div class="page-header">
      <el-button type="primary" :icon="Plus" @click="handleAddExperience">
        添加经历
      </el-button>
    </div>

    <!-- 时间轴展示 -->
    <el-timeline v-loading="loading">
      <el-timeline-item v-for="(exp, index) in experiences" :key="exp.id || index"
        :timestamp="formatPeriod(exp.startDate, exp.endDate)" placement="top" :type="getType(index)" size="large">
        <el-card shadow="hover">
          <div class="experience-content">
            <div class="experience-header">
              <div class="company-info">
                <h3>{{ exp.company }}</h3>
                <p class="position">{{ exp.position }}</p>
                <p class="department" v-if="exp.department">{{ exp.department }}</p>
                <div class="meta-info">
                  <p class="salary" v-if="exp.salaryRange">薪资：{{ exp.salaryRange }}</p>
                <el-tag :type="exp.isCurrent === 1 ? 'success' : 'danger'" size="small">
                  {{ exp.isCurrent === 1 ? '在职中' : '已离职' }}
                </el-tag>
                </div>
              </div>
              <div class="experience-actions">
                <el-button size="small" :icon="View" @click="handleViewExperience(exp)">查看</el-button>
                <el-button size="small" :icon="Edit" @click="handleEditExperience(exp)">编辑</el-button>
                <el-button size="small" :icon="Delete" type="danger" @click="handleDeleteExperience(exp)">删除</el-button>
              </div>
            </div>

            <div class="description" v-if="exp.description">
              <h4>工作描述</h4>
              <p>{{ exp.description }}</p>
            </div>

            <div class="achievements" v-if="exp.achievements && exp.achievements.trim()">
              <div class="achievements-header">
                <h4>主要成就</h4>
                <el-icon class="achievement-icon">
                  <Trophy />
                </el-icon>
              </div>
              <div class="achievements-content">
                <div class="achievement-item">
                  <div class="achievement-text">{{ exp.achievements }}</div>
                </div>
              </div>
            </div>

            
          </div>
        </el-card>
      </el-timeline-item>
    </el-timeline>

    <!-- 经历表单弹窗 -->
    <el-dialog v-model="experienceFormVisible" :title="experienceFormMode === 'add' ? '添加工作经历' : '编辑工作经历'" width="800px"
      @close="resetExperienceForm">
      <div class="experience-form-content">
        <el-form ref="experienceFormRef" :model="experienceForm" :rules="experienceFormRules" label-width="120px"
          status-icon>

          <el-form-item label="公司名称" prop="company">
            <el-input v-model="experienceForm.company" placeholder="请输入公司名称" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="职位" prop="position">
            <el-input v-model="experienceForm.position" placeholder="请输入职位" maxlength="100" show-word-limit />
          </el-form-item>

          <el-form-item label="部门" prop="department">
            <el-input v-model="experienceForm.department" placeholder="请输入部门" maxlength="100" show-word-limit />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startDate">
                <el-date-picker v-model="experienceForm.startDate" type="date" placeholder="选择开始时间"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endDate">
                <el-date-picker v-model="experienceForm.endDate" type="date" placeholder="选择结束时间（留空表示至今）"
                  style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="薪资范围" prop="salaryRange">
            <el-input v-model="experienceForm.salaryRange" placeholder="如：15K-25K" maxlength="50" />
          </el-form-item>

          <el-form-item label="工作状态" prop="isCurrent">
            <el-select v-model="experienceForm.isCurrent" placeholder="请选择工作状态" style="width: 100%" @change="handleStatusChange">
              <el-option label="在职中" :value="1" />
              <el-option label="已离职" :value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="工作描述" prop="description">
            <el-input v-model="experienceForm.description" type="textarea" :rows="3" placeholder="请描述工作内容和职责"
              maxlength="1000" show-word-limit />
          </el-form-item>

          <el-form-item label="主要成就" prop="achievements">
            <el-input v-model="experienceForm.achievements" type="textarea" :rows="4" placeholder="请输入主要成就，每行一个成就，建议格式：
1. 重构核心业务系统，性能提升40%
2. 建立前端工程化体系
3. 指导5名初级开发者成长

或者使用自然换行方式输入，每个成就一行" />
          </el-form-item>

          

        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="experienceFormVisible = false">取消</el-button>
          <el-button type="primary" @click="submitExperienceForm">
            {{ experienceFormMode === 'add' ? '添加' : '更新' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 经历详情查看弹窗 -->
    <el-dialog v-model="experienceDetailVisible" title="经历详情" width="900px" :close-on-click-modal="false">
      <div class="experience-detail-content" v-if="selectedExperience">
        <!-- 经历标题区域 -->
        <div class="experience-header">
          <div class="experience-title">
            <h2>{{ selectedExperience.company }}</h2>
            <div class="experience-tags">
              <el-tag size="large" effect="plain">
                {{ selectedExperience.position }}
              </el-tag>
              <el-tag size="large" :type="selectedExperience.status === '在职中' ? 'success' : 'danger'">
                {{ selectedExperience.status }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 经历基本信息 -->
        <div class="info-sections">
          <el-card class="info-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>基本信息</span>
              </div>
            </template>

            <div class="info-grid">
              <div class="info-item">
                <label>公司名称</label>
                <div class="info-value">{{ selectedExperience.company }}</div>
              </div>

              <div class="info-item">
                <label>职位</label>
                <div class="info-value">{{ selectedExperience.position }}</div>
              </div>

              <div class="info-item">
                <label>部门</label>
                <div class="info-value">{{ selectedExperience.department || '未填写' }}</div>
              </div>

              <div class="info-item">
                <label>工作期间</label>
                <div class="info-value">
                  {{ formatPeriod(selectedExperience.startDate, selectedExperience.endDate) }}
                </div>
              </div>

              <div class="info-item">
                <label>薪资范围</label>
                <div class="info-value">{{ selectedExperience.salaryRange || '未填写' }}</div>
              </div>

              <div class="info-item">
                <label>工作状态</label>
                <div class="info-value">
                  <el-tag :type="selectedExperience.isCurrent === 1 ? 'success' : 'danger'" size="small">
                    {{ selectedExperience.isCurrent === 1 ? '在职中' : '已离职' }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>

          <el-card class="info-card" shadow="hover" v-if="selectedExperience.description">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <Document />
                </el-icon>
                <span>工作描述</span>
              </div>
            </template>

            <div class="description-content">
              <p>{{ selectedExperience.description }}</p>
            </div>
          </el-card>

          <el-card class="info-card" shadow="hover"
            v-if="selectedExperience.achievements && selectedExperience.achievements.trim()">
            <template #header>
              <div class="card-header">
                <el-icon>
                  <Trophy />
                </el-icon>
                <span>主要成就</span>
              </div>
            </template>

            <div class="achievements-content">
              <div class="achievement-item">
                <div class="achievement-text">{{ selectedExperience.achievements }}</div>
              </div>
            </div>
          </el-card>

          
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="experienceDetailVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Edit, Delete, View, InfoFilled, Document, Trophy } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { experienceApi } from '@/utils/api/experience'

// 响应式数据
const loading = ref(false)
const experiences = ref([])

// 经历表单相关数据
const experienceFormVisible = ref(false)
const experienceFormMode = ref('add') // 'add' 或 'edit'
const experienceFormRef = ref()
const experienceForm = reactive({
  id: null,
  company: '',
  position: '',
  department: '',
  startDate: '',
  endDate: '',
  salaryRange: '',
  isCurrent: 1,
  description: '',
  achievements: ''
})



const experienceFormRules = {
  company: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 1, max: 100, message: '公司名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' },
    { min: 1, max: 100, message: '职位长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  startDate: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  isCurrent: [
    { required: true, message: '请选择工作状态', trigger: 'change' }
  ],
  description: [
    { max: 1000, message: '工作描述长度不能超过 1000 个字符', trigger: 'blur' }
  ]
}

// 经历详情查看相关数据
const experienceDetailVisible = ref(false)
const selectedExperience = ref(null)

// 加载经历数据
const loadExperiences = async () => {
  try {
    loading.value = true
    const response = await experienceApi.queryList({})
    if (response.code === 0) {
      experiences.value = response.data
    } else {
      ElMessage.error(response.message || '加载经历列表失败')
    }
  } catch (error) {
    console.error('加载经历列表失败:', error)
    ElMessage.error('加载经历列表失败')
  } finally {
    loading.value = false
  }
}



// 生命周期钩子
onMounted(() => {
  loadExperiences()
})

// 工具函数
const getType = (index) => {
  const types = ['primary', 'success', 'warning']
  return types[index % types.length]
}

const formatPeriod = (startDate, endDate) => {
  if (!startDate) return ''
  const formatDate = (dateStr) => {
    if (!dateStr) return ''
    try {
      const date = new Date(dateStr)
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit' 
      })
    } catch {
      return dateStr
    }
  }
  
  if (endDate) {
    return `${formatDate(startDate)} - ${formatDate(endDate)}`
  } else {
    return `${formatDate(startDate)} - 至今`
  }
}

const handleStatusChange = (value) => {
  if (value === 1) {
    // 选择在职中时，清空结束时间
    experienceForm.endDate = ''
  }
}

// 方法
const handleAddExperience = () => {
  experienceFormMode.value = 'add'
  resetExperienceForm()
  experienceFormVisible.value = true
}

const handleViewExperience = (experience) => {
  selectedExperience.value = { ...experience }
  experienceDetailVisible.value = true
}

const handleEditExperience = (experience) => {
  experienceFormMode.value = 'edit'
  // 填充表单数据
  experienceForm.id = experience.id
  experienceForm.company = experience.company
  experienceForm.position = experience.position
  experienceForm.department = experience.department || ''
  experienceForm.startDate = experience.startDate
  experienceForm.endDate = experience.endDate
  experienceForm.salaryRange = experience.salaryRange || ''
  experienceForm.isCurrent = experience.isCurrent || 0
  experienceForm.description = experience.description || ''
  experienceForm.achievements = experience.achievements || ''

  experienceFormVisible.value = true
}

const handleDeleteExperience = async (experience) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工作经历「${experience.company} - ${experience.position}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await experienceApi.delete(experience.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      loadExperiences()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除工作经历失败:', error)
      ElMessage.error('删除工作经历失败')
    }
  }
}

// 表单方法
const submitExperienceForm = async () => {
  if (!experienceFormRef.value) return

  try {
    await experienceFormRef.value.validate()

    const apiData = {
      company: experienceForm.company.trim(),
      position: experienceForm.position.trim(),
      department: experienceForm.department?.trim() || '',
      startDate: experienceForm.startDate,
      endDate: experienceForm.isCurrent === 1 ? null : experienceForm.endDate,
      salaryRange: experienceForm.salaryRange?.trim() || '',
      isCurrent: experienceForm.isCurrent,
      description: experienceForm.description?.trim() || '',
      achievements: experienceForm.achievements
    }

    let response
    if (experienceFormMode.value === 'add') {
      response = await experienceApi.create(apiData)
    } else {
      response = await experienceApi.update(experienceForm.id, apiData)
    }

    if (response.code === 0) {
      ElMessage.success(experienceFormMode.value === 'add' ? '添加工作经历成功' : '更新工作经历成功')
      experienceFormVisible.value = false
      loadExperiences()
    } else {
      ElMessage.error(response.message || (experienceFormMode.value === 'add' ? '添加工作经历失败' : '更新工作经历失败'))
    }
  } catch (error) {
    console.error('提交工作经历表单失败:', error)
    if (error !== false) { // 验证失败时不显示错误
      ElMessage.error(experienceFormMode.value === 'add' ? '添加工作经历失败' : '更新工作经历失败')
    }
  }
}

const resetExperienceForm = () => {
  if (experienceFormRef.value) {
    experienceFormRef.value.resetFields()
  }

  experienceForm.id = null
  experienceForm.company = ''
  experienceForm.position = ''
  experienceForm.department = ''
  experienceForm.startDate = ''
  experienceForm.endDate = ''
  experienceForm.salaryRange = ''
  experienceForm.isCurrent = 1
  experienceForm.description = ''
  experienceForm.achievements = ''
}
</script>

<style scoped>
.experience-page {
  padding: 0;
}

/* 顶部操作栏 */
.page-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 24px;
}

.experience-content {
  padding: 0;
}

.experience-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.company-info h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.company-info .position {
  font-size: 16px;
  color: #409eff;
  margin-bottom: 4px;
}

.company-info .department {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.meta-info .salary {
  font-size: 14px;
  color: #606266;
}

.experience-actions {
  display: flex;
  gap: 8px;
}

.description {
  margin-bottom: 20px;
}

.description h4 {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin-bottom: 12px;
}

.description p {
  color: #606266;
  line-height: 1.6;
  margin: 0;
  white-space: pre-wrap;
}

.achievements {
  margin-bottom: 20px;
}

.achievements-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.achievements h4 {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
  margin: 0;
}

.achievement-icon {
  color: #e6a23c;
  font-size: 16px;
}



/* 表单弹窗样式 */
.experience-form-content {
  max-height: calc(80vh - 180px);
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 4px;
}

/* 详情弹窗样式 */
.experience-detail-content {
  padding: 0;
  max-height: calc(90vh - 240px);
  overflow-y: auto;
  overflow-x: hidden;
}

.experience-title h2 {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.experience-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.info-sections {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-card {
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.card-header .el-icon {
  color: #409EFF;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.info-value {
  font-size: 16px;
  color: #303133;
}

.description-content,
.achievements-content {
  color: #303133;
  line-height: 1.6;
  font-size: 14px;
}

.achievement-item {
  padding: 16px 20px;
  background: #f8f9fa;
  border-radius: 12px;
  border-left: 4px solid #409eff;
  transition: all 0.3s ease;
}

.achievement-item:hover {
  background: #f0f9ff;
  border-left-color: #67c23a;
  transform: translateX(2px);
}

.achievement-text {
  color: #303133;
  line-height: 1.7;
  font-size: 15px;
  font-weight: 500;
  white-space: pre-wrap;
}

.description-content p {
  margin: 0;
  white-space: pre-wrap;
}



.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-dialog {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .experience-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>